<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount, useTemplateRef } from "vue";
import Toolbox from "./components/Toolbox.vue";
import { ElMessage } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import IssueDrawer from "./components/IssueDrawer.vue";
import UpdateDownloadProgress from "./components/UpdateDownloadProgress.vue";

const locale = ref(zhCn);
const showWebview = ref(false);
const webviewRef = ref(null);
const webviewPreloadPath = ref("");
const showTools = ref(false);
const issueDrawerRef = ref(null);
const toolboxRef = useTemplateRef();

// 下载飞行动画相关
const showDownloadFly = ref(false);
const flyStyle = ref({});
const flyTransform = ref("translate(0,0)");

let webviewSrc = "https://pm.yichenghbkj.com/home/";
if (import.meta.env.VITE_NODE_ENV === "development") {
  webviewSrc = "http://192.168.3.54:8080/#/";
}

async function triggerDownloadFly() {
  const start = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
  let end = { x: window.innerWidth - 60, y: 60 };
  const toolbox = toolboxRef.value;
  let targetBtn = null;
  if (toolbox && toolbox.isExpanded.value) {
    targetBtn =
      toolbox.toolBtnRefs.value["downloads"]?.$el ||
      toolbox.toolBtnRefs.value["downloads"];
  } else if (toolbox && toolbox.mainBtnRef.value) {
    targetBtn = toolbox.mainBtnRef.value?.$el || toolbox.mainBtnRef.value;
  }
  if (targetBtn) {
    const rect = targetBtn.getBoundingClientRect();
    end = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  }
  // 初始位置
  flyStyle.value = {
    left: `${start.x}px`,
    top: `${start.y}px`,
  };
  flyTransform.value = "translate(0,0)";
  showDownloadFly.value = true;
  await nextTick();
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      flyTransform.value = `translate(${end.x - start.x}px, ${
        end.y - start.y
      }px)`;
    });
  });
  setTimeout(() => {
    showDownloadFly.value = false;
  }, 700);
}

onMounted(async () => {
  // 获取 webview-preload.js 的绝对路径
  const preloadPath = await window.electronAPI.getWebviewPreloadPath();
  // 赋值给 webview 的 preload 属性
  webviewPreloadPath.value = preloadPath;
  // 注册监听事件
  nextTick(registerEventListener);
  window.addEventListener("dragover", preventDrop, false);
  window.addEventListener("drop", preventDrop, false);
  
  if (window.electronAPI?.onDownloadProgress) {
    window.electronAPI.onDownloadProgress((data) => {
      if (data.action === "add") {
        triggerDownloadFly();
      }
    });
  }
});

onBeforeUnmount(() => {
  window.removeEventListener("dragover", preventDrop, false);
  window.removeEventListener("drop", preventDrop, false);
  window.electronAPI?.onToWebViewPaste?.(null);
});

const registerEventListener = () => {
  const webview = webviewRef.value;
  webview.addEventListener("did-fail-load", (event) => {
    console.error("Webview failed to load:", event);
  });

  webview.addEventListener("did-start-loading", () => {
    console.log("Webview started loading");
  });

  webview.addEventListener("did-stop-loading", () => {
    console.log("Webview stopped loading");
    // webview 加载完成，关闭加载动画
    closeLoadingAnimate();
  });

  webview.addEventListener("dom-ready", () => {
    console.log("Webview dom ready");
  });
  // 监听主进程消息并转发到 webview
  window.electronAPI.onToWebViewPaste((imgSrc, data) => {
    webview.send("electron-screenshot-paste", imgSrc, data);
    if (issueDrawerRef.value) {
      issueDrawerRef.value.handlePaste(imgSrc);
    }
  });
  // 聊天室开关
  window.electronAPI.onToggleChatroom(toggleChatroomShow);
  // 监听打开webview控制台
  window.electronAPI.onOpenWebViewDevTools(() => {
    if (webview && typeof webview.openDevTools === "function") {
      webview.openDevTools();
    } else {
      console.error("webview or openDevTools not available", webview);
    }
  });
  // 监听刷新webview
  window.electronAPI.onRefreshWebIgnoreCache(refreshIgnoreCache);
  // 监听打开/关闭工具箱 data -Boolean
  window.electronAPI.onToogleToolbox((data) => {
    showTools.value = data;
  });
};
const closeLoadingAnimate = () => {
  // 获取id为loader的div，并将其从文档中移除
  const loaderDiv = document.getElementById("uiverse-loader");
  if (loaderDiv && loaderDiv.parentNode) {
    loaderDiv.parentNode.removeChild(loaderDiv);
  }
  const loaderSvg = document.getElementById("uiverse-loader-svg");
  if (loaderSvg && loaderSvg.parentNode) {
    loaderSvg.parentNode.removeChild(loaderSvg);
  }
  showWebview.value = true;
};
// 控制打开/关闭聊天室
const toggleChatroomShow = async () => {
  const result = await webviewRef.value.executeJavaScript(
    "onPmRegisterToggleChatroom('pm-app-webview')"
  );
  if (!result || !result.data) {
    ElMessage.error(result?.message || "打开失败");
  }
};
// 去缓存刷新webview网页
const refreshIgnoreCache = () => {
  const webview = webviewRef.value;
  if (webview && typeof webview.reloadIgnoringCache === "function") {
    webview.reloadIgnoringCache();
  } else {
    console.error("webview or reloadIgnoringCache not available", webview);
  }
};
// 返回上一页
const backToPrePage = () => {
  webviewRef.value.executeJavaScript("onPmBackPrePage('pm-app-webview')");
};
function openIssueDrawer() {
  issueDrawerRef.value?.open();
}
// 禁止文件/文件夹拖入
function preventDrop(e) {
  e.preventDefault();
}
</script>

<template>
  <el-config-provider :locale="locale">
    <div
      v-if="showDownloadFly"
      class="download-fly-icon"
      :style="{ ...flyStyle, transform: flyTransform }"
    >
      <el-icon>
        <Download />
      </el-icon>
    </div>
    <webview
      v-if="webviewPreloadPath"
      ref="webviewRef"
      :src="webviewSrc"
      v-show="showWebview"
      :preload="webviewPreloadPath"
      nodeintegration="false"
      contextisolation="true"
      sandbox="false"
      allowrunninginsecurecontent="true"
      websecurity="false"
    />
    <Toolbox
      v-if="showTools"
      ref="toolboxRef"
      :webview="webviewRef"
      @toggleChatroom="toggleChatroomShow"
      @refresh="refreshIgnoreCache"
      @back="backToPrePage"
      @openIssueDrawer="openIssueDrawer"
    />
    <IssueDrawer ref="issueDrawerRef" />
    <UpdateDownloadProgress />
  </el-config-provider>
</template>

<style scoped lang="scss">
webview {
  width: 100vw;
  height: 100vh;
  border: none;
}

.download-fly-icon {
  position: fixed;
  z-index: 99;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #409eff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  left: 50vw;
  top: 50vh;
  pointer-events: none;
  transition: transform 0.5s cubic-bezier(0.4, 1, 0.7, 1), opacity 0.3s;
  opacity: 1;
  will-change: transform;
}
</style>
